<template>
  <div>
    <de-container class="pa-5">
      <avue-crud
        ref="crud"
        v-model="form"
        :data="tableData"
        :table-loading="tableLoading"
        :option="tableOption"
        :search.sync="searchForm"
        :before-open="beforeOpen"
        :permission="getPermission"
        @on-load="loadListData"
        @search-change="onSearchChange"
        @search-reset="onSearchReset"
        @row-save="onRowSave"
        @row-update="onRowUpdate"
        @row-del="onRowDelete"
        @refresh-change="onRefresh"
        @selection-change="onSelectionChange"
        @filter-change="onFilterChange"
        @sort-change="onSortChange"
      >
        <template slot="menu" slot-scope="{ row, size, type }">
          <el-button :type="type" icon="el-icon-plus" :size="size" @click="handleAdd(row)">增加子分类</el-button>
        </template>
        <template slot="sequenceLabel">
          <span>排序&nbsp;</span>
          <el-tooltip class="item" effect="dark" content="序号越小越靠前" placement="top">
            <i class="el-icon-warning"></i>
          </el-tooltip>
        </template>
      </avue-crud>
    </de-container>
  </div>
</template>

<script>
import { tableOption } from './tableOption'
import ListMixin from '@/utils/mixins/list-mixin'
import { requestInfoTypeTree, requestInfoTypeAdd, requestInfoTypeEdit, requesInfoTypeDelete } from '@/api/information'
import DeContainer from '@/components/dataease/DeContainer.vue'

export default {
  name: 'Type',
  components: { DeContainer },
  mixins: [ListMixin],
  data() {
    return {
      listApi: requestInfoTypeTree,
      createApi: requestInfoTypeAdd,
      updateApi: requestInfoTypeEdit,
      deleteApi: requesInfoTypeDelete,
      tableOption,
    }
  },
  methods: {
    getPermission(key, row, index) {
      if ((key === 'editBtn' || key === 'delBtn') && row.level == 1) {
        return false
      }
      return true
    },
    handleAdd(row) {
      this.form.parentId = row.id
      this.$refs.crud.rowAdd()
    },
    formateTreeData(data) {
      let arr = []
      data.forEach((item) => {
        if (item.childrenList || item.childrenList === null) {
          const children = formateTreeData(item.childrenList)
          if (children !== undefined) {
            item.children = children
            delete item.childrenList
          }
        }
        arr.push(item)
      })
      return arr
    },

    loadListData() {
      this.tableLoading = true
      this.searchForm.parentId = 0
      return requestInfoTypeTree(this.searchForm)
        .then((res) => {
          this.tableData = res.data
        })
        .catch((error) => {
          this.$message({
            type: 'error',
            message: res.message,
          })
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
  },
}
</script>
<style lang="scss"></style>
